﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using bdnt_pets_system.SystemServiceReference;
using System.Windows.Media.Imaging;
using System.IO;
using bdnt_pets_system.FrameViews;
using bdnt_pets_system.Resources;
using System.Windows.Data;
using bdnt_pets_system.Tools;
using System.Globalization;
using bdnt_pets_system_Entity;

namespace bdnt_pets_system.PageViews.SystemViews
{
    public partial class MenuManageControl : BaseUserControl
    {
        SystemServiceReference.SystemServiceClient sysClient;
        public MenuManageControl()
        {
            InitializeComponent();
            sysClient = new SystemServiceReference.SystemServiceClient();
            InitEvent();
            QueryData();
        }

        void InitEvent()
        {
            sysClient.GetAllMenuListCompleted += new EventHandler<SystemServiceReference.GetAllMenuListCompletedEventArgs>(sysClient_GetAllMenuListCompleted);
            sysClient.DeleteMenuObjCompleted += new EventHandler<DeleteMenuObjCompletedEventArgs>(sysClient_DeleteMenuObjCompleted);
            btnNewMenu.Click += new RoutedEventHandler(btnNewMenu_Click);
            btnUpdateMenu.Click += new RoutedEventHandler(btnUpdateMenu_Click);
            btnDeleteMenu.Click += new RoutedEventHandler(btnDeleteMenu_Click);
        }

        void sysClient_DeleteMenuObjCompleted(object sender, DeleteMenuObjCompletedEventArgs e)
        {
            if (e.Result)
                QueryData();
            else
                tbErrorMsg.SetBinding(TextBlock.TextProperty, new Binding("Strings.czsb") { Source = CuLc });
        }

        void btnDeleteMenu_Click(object sender, RoutedEventArgs e)
        {
            if (tvMenu.SelectedItem == null)
            {
                tbErrorMsg.SetBinding(TextBlock.TextProperty, new Binding("Strings.qxzsccd") { Source = CuLc });
                return;
            }
            if (MessageBox.Show(MyStrings.qdyscm,MyStrings.ts, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            var item = (tvMenu.SelectedItem as TreeViewItem).DataContext as Tbl_Menu;
            selectMId = item.PMenuId == 0 ? 1 : item.PMenuId;
            isExpSelectM = true;
            sysClient.DeleteMenuObjAsync(item.Id);
        }

        void btnUpdateMenu_Click(object sender, RoutedEventArgs e)
        {
            if (tvMenu.SelectedItem != null)
            {
                var item = (tvMenu.SelectedItem as TreeViewItem).DataContext as Tbl_Menu;
                var cuP = SessionManager.RoleAllMenus.FirstOrDefault(p => p.Id == item.PMenuId);
                item.PMenuName = cuP != null ? cuP.MenuName : "";
                var cupage = new NewMenuControl(item);
                App.ToPage(cupage);//跳转页面
            }
            else
                tbErrorMsg.Text = MyStrings.ResourceManager.GetString("qxzxgcd");
        }

        void btnNewMenu_Click(object sender, RoutedEventArgs e)
        {
            if (tvMenu.SelectedItem != null)
            {
                var item = (tvMenu.SelectedItem as TreeViewItem).DataContext as Tbl_Menu;
                var cupage = new NewMenuControl(new Tbl_Menu()
                {
                    PMenuId = item.Id,
                    PMenuName = item.MenuName,
                    MenuType = 0
                });
                App.ToPage(cupage);//跳转页面
            }
            else
                tbErrorMsg.SetBinding(TextBlock.TextProperty, new Binding("Strings.qxzfjcd") { Source = CuLc });

        }

        void QueryData()
        {
            sysClient.GetAllMenuListAsync();
        }

        void sysClient_GetAllMenuListCompleted(object sender, SystemServiceReference.GetAllMenuListCompletedEventArgs e)
        {
            SessionManager.AllMenus = e.Result;
            InitMenus();
        }

        public int selectMId = 1;
        public bool isExpSelectM = true;

        void InitMenus()
        {
            var allMenus = SessionManager.AllMenus;
            if (allMenus.Count == 0)
                return;
            tvMenu.Items.Clear();
            expMIds.Clear();
            GetExpMs(selectMId);

            var pMs = allMenus.Where(p => p.PMenuId == 0).OrderBy(p => p.MenuSequence);
            foreach (var item in pMs)
            {
                TreeViewItem cuI = new TreeViewItem();

                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
                if (item.Icon != null && item.Icon.Length > 0)
                {
                    Image img = new Image() { Height = 16, Width = 16, Margin = new Thickness(0, 0, 4, 0) };
                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(item.Icon, 0, item.Icon.Length);
                    b.SetSource(mm);
                    img.Source = b;
                    mm.Close();
                    mm.Dispose();
                    //using (MemoryStream stream = new MemoryStream(item.Icon))
                    //{
                    //    stream.Seek(0, SeekOrigin.Begin);
                    //    BitmapImage b2 = new BitmapImage();
                    //    b2.SetSource(stream);
                    //    img.Source = b2;
                    //}
                    sp.Children.Add(img);
                }

                TextBlock tb = new TextBlock() { FontSize = 12 };
                sp.Children.Add(tb);

                tb.Text = SessionManager.IsCN_ZH ? (item.MenuName + "[" + MyStrings.ResourceManager.GetString("paixu")
                    + item.MenuSequence + "]:" + item.MenuModule) : (item.en_MenuName + "[" + MyStrings.ResourceManager.GetString("paixu")
                    + item.MenuSequence + "]:" + item.MenuModule);

                cuI.Header = sp;
                cuI.DataContext = item;
                AddChildNode(cuI, item, allMenus);

                cuI.IsExpanded = expMIds.Contains(item.Id) ? true : false;
                if (selectMId == item.Id)
                {
                    cuI.IsSelected = true;
                    cuI.IsExpanded = isExpSelectM;
                }

                tvMenu.Items.Add(cuI);
            }
        }

        List<int> expMIds = new List<int>();
        void GetExpMs(int selectMId)
        {
            var allMenus = SessionManager.AllMenus;
            if (allMenus.Count == 0)
                return;
            var cuo = allMenus.FirstOrDefault(p => p.Id == selectMId);
            if (cuo != null)
            {
                expMIds.Add(cuo.PMenuId);
                GetExpMs(cuo.PMenuId);
            }
        }
        void AddChildNode(TreeViewItem pitem, Tbl_Menu pmenu, ObservableCollection<Tbl_Menu> source)
        {
            var cuos = source.Where(c => c.PMenuId == pmenu.Id).OrderBy(p => p.MenuSequence);
            foreach (var item in cuos)
            {
                TreeViewItem cuI = new TreeViewItem();
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
                if (item.Icon != null && item.Icon.Length > 0)
                {
                    Image img = new Image() { Height = 16, Width = 16, Margin = new Thickness(0, 0, 4, 0) };
                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(item.Icon, 0, item.Icon.Length);
                    b.SetSource(mm);
                    img.Source = b;
                    mm.Close();
                    mm.Dispose();
                    sp.Children.Add(img);
                }
                TextBlock tb = new TextBlock() { FontSize = 12 };
                sp.Children.Add(tb);

                tb.Text = SessionManager.IsCN_ZH ? (item.MenuName + "[" + MyStrings.ResourceManager.GetString("paixu")
                    + item.MenuSequence + "]:" + item.MenuModule) : (item.en_MenuName + "[" + MyStrings.ResourceManager.GetString("paixu")
                    + item.MenuSequence + "]:" + item.MenuModule);

                cuI.Header = sp;
                cuI.DataContext = item;
                AddChildNode(cuI, item, source);

                cuI.IsExpanded = expMIds.Contains(item.Id) ? true : false;
                if (selectMId == item.Id)
                {
                    cuI.IsSelected = true;
                    cuI.IsExpanded = isExpSelectM;
                }
                pitem.Items.Add(cuI);
            }
        }
    }
}
